package com.simon.hse.activity.contractor;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.google.gson.Gson;
import com.simon.hse.http.Constants;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonAdapter;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.AddTrainRecordInput;
import com.simon.hse.http.entity.CommonOutput;
import com.simon.hse.http.entity.ContractorPersonOutput;
import com.simon.hse.http.entity.TrainCourseOutput;
import com.simon.hse.http.entity.TrainPersonOutput;
import com.simon.hse.http.entity.TrainRecordDetailOutput;
import com.simon.hse.http.entity.TrainRecordOutput;
import com.simon.hse.http.entity.UploadFileOutput;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.SelectPicUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 添加培训记录
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_add_train_record)
public class AddTrainRecordActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_train_record_name)
    LinearLayout mLl_train_record_name;

    @ViewInject(R.id.tv_train_record_name)
    TextView mTv_train_record_name;

    @ViewInject(R.id.ll_train_person)
    LinearLayout mLl_train_person;

    @ViewInject(R.id.tv_train_person)
    TextView mTv_train_person;

    @ViewInject(R.id.ll_train_date)
    LinearLayout mLl_train_date;

    @ViewInject(R.id.tv_train_date)
    TextView mTv_train_date;

    @ViewInject(R.id.et_train_record_remark)
    EditText mEt_train_record_remark;

    @ViewInject(R.id.ll_train_participant)
    LinearLayout mLl_train_participant;

    @ViewInject(R.id.tv_train_participant)
    TextView mTv_train_participant;

    @ViewInject(R.id.rv_pic)
    RecyclerView mRv_pic;

    private String id;
    private TrainRecordOutput.DataBean.PageDataBean pageDataBean;
    //上传图片
    private String trainCourseId, trainPersonId, participantName, participantId;
    private CommonAdapter mCommonAdapter;
    private List<String> mPicList = new ArrayList<>();
    private List<String> mPicIdList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPicRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_train_record_name, R.id.ll_train_person, R.id.ll_train_date, R.id.ll_train_participant
            , R.id.ll_add_train_record_pic, R.id.tv_train_record_cancel, R.id.tv_train_record_confirm,R.id.iv_add_train_record_pic})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                setResult(RESULT_OK, new Intent());
                finish();
                break;
            case R.id.ll_train_record_name:
                initTrainCoursePop();
                break;
            case R.id.ll_train_person:
                initTrainPersonPop(mTv_train_person, mLl_train_person);
                break;
            case R.id.ll_train_date:
                initTrainTime();
                break;
            case R.id.ll_train_participant:
                // initParticipantPop(mTv_train_participant, mLl_train_participant);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.setClass(AddTrainRecordActivity.this, ConstractorPersonActivity.class);
                bundle.putString("TITLE", "参与人员选取");
                bundle.putString("NAME", "");
                bundle.putString("ID", "");
                bundle.putString("NAME1", participantName);
                bundle.putString("ID1", participantId);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;
            case R.id.iv_add_train_record_pic:
                SelectPicUtils.takePic(AddTrainRecordActivity.this, SelectPicUtils.REQUEST_CODE_CHOOSE);
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .start(AddTrainRecordActivity.this, Constants.REQUEST_CODE); // 打开相册
                break;
            case R.id.tv_train_record_cancel:
                finish();
                break;
            case R.id.tv_train_record_confirm:
                submit();
                break;
        }
    }

    private void initPicRecyclerView() {
        GridLayoutManager glm = new GridLayoutManager(AddTrainRecordActivity.this, 4);
        mRv_pic.setLayoutManager(glm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        mCommonAdapter = new CommonAdapter(AddTrainRecordActivity.this, R.layout.layout_item_pic, mPicList);
        mCommonAdapter.setItemDatasListener(new CommonAdapter.ItemDatasListener<String>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, String uri, int position) {
                ImageView iv_item = holder.getView(R.id.iv_item);
                Glide.with(AddTrainRecordActivity.this).load(uri).into(iv_item);
            }
        });

        mCommonAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {
                mPicList.remove(position);
                mPicIdList.remove(position);
                mCommonAdapter.notifyDataSetChanged();
            }
        });

        mRv_pic.setAdapter(mCommonAdapter);
    }

    private void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            mTv_common_title.setText("新增培训记录");
            mTv_train_date.setText(DateTimeUtils.getCurrentYMD());
        } else {
            mTv_common_title.setText("修改培训记录");
            pageDataBean = (TrainRecordOutput.DataBean.PageDataBean) extras.getSerializable("RECORD_DATA");

            id = pageDataBean.getId();
            initTrainRecordDetail();
            mTv_train_record_name.setText(pageDataBean.getTrainingCoursewareName());
            mTv_train_person.setText(pageDataBean.getTrainerText());
            String trainingDate = pageDataBean.getTrainingDate();
            if (trainingDate.contains(" ")) {
                String[] split = trainingDate.split(" ");
                trainingDate = split[0];
            }
            mTv_train_date.setText(trainingDate);
            List<String> recordUser = pageDataBean.getCbS_TrainRecordUser();
            StringBuffer sb = new StringBuffer();
            for (String s : recordUser) {
                sb.append(s + "、");
            }
            mTv_train_participant.setText(sb.toString());
            mEt_train_record_remark.setText(pageDataBean.getRemarks());
        }
    }

    /**
     * 培训记录详情
     */
    private void initTrainRecordDetail() {
        Call<String> call = HttpManager.getInstance().requestService().CONTRACTOR_TRAIN_RECORD_DETAIL(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                TrainRecordDetailOutput trainRecordDetailOutput = new Gson().fromJson(result, TrainRecordDetailOutput.class);
                if (trainRecordDetailOutput.getResult().equals("Success")) {
                    TrainRecordDetailOutput.DataBean dataBean = trainRecordDetailOutput.getData();
                    trainCourseId = dataBean.getCbsCourseId();
                    trainPersonId = dataBean.getTrainer();
                    List<String> list = dataBean.getCbS_TrainRecordUser();
                    if (!list.isEmpty()) {
                        StringBuffer sb = new StringBuffer();
                        for (String s : list) {
                            sb.append(s + ",");
                        }
                        participantId = sb.toString();
                    }
                    String annex = dataBean.getAnnex();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(trainRecordDetailOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 课件名称
     */
    private void initTrainCoursePop() {
        View inflate = LayoutInflater.from(AddTrainRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRv_pic = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddTrainRecordActivity.this);
        mRv_pic.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddTrainRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListTrainCourse);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainCourseOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainCourseOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getTrainingCoursewareName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainCourseOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListTrainCourse.get(position);
                String trainCourseName = pageDataBean.getTrainingCoursewareName();
                trainCourseId = pageDataBean.getId();
                mTv_train_record_name.setText(trainCourseName);
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRv_pic.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddTrainRecordActivity.this, inflate, mLl_train_record_name);
    }

    /**
     * 培训人
     */
    private void initTrainPersonPop(final TextView textView, LinearLayout linearLayout) {
        View inflate = LayoutInflater.from(AddTrainRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRv_pic = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddTrainRecordActivity.this);
        mRv_pic.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddTrainRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListTrainPerson);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainPersonOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListTrainPerson.get(position);
                trainPersonId = pageDataBean.getId();
                textView.setText(pageDataBean.getName());
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRv_pic.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddTrainRecordActivity.this, inflate, linearLayout);
    }

    /**
     * 参与人
     */
    private void initParticipantPop(final TextView textView, LinearLayout linearLayout) {
        View inflate = LayoutInflater.from(AddTrainRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRv_pic = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddTrainRecordActivity.this);
        mRv_pic.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddTrainRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListParticipant);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<ContractorPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, ContractorPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getPersonnelName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                ContractorPersonOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListParticipant.get(position);
                participantId = pageDataBean.getId();
                participantName = pageDataBean.getPersonnelName();
                textView.setText(participantName);
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRv_pic.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddTrainRecordActivity.this, inflate, linearLayout);
    }

    /**
     * 出厂时间
     */
    private void initTrainTime() {
        Calendar selectedDate = Calendar.getInstance();
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");// HH:mm
                mTv_train_date.setText(sdf_ymd.format(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setTitleSize(20)//标题文字大小
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

        pvTime.show();
    }

    /**
     * 提交
     */
    private void submit() {
        StringBuffer sbPicId = new StringBuffer();
        for (String picId : mPicIdList) {
            sbPicId.append(picId + " ");
        }
        String trainCourseName = mTv_train_record_name.getText().toString();
        String trainPerson = mTv_train_person.getText().toString();
        String participant = mTv_train_participant.getText().toString();
        String date = mTv_train_date.getText().toString();
        String remark = mEt_train_record_remark.getText().toString();
        if (TextUtils.isEmpty(trainCourseName)) {
            ToastUtils.getInstance().showShortToastBottom("请选择培训课件名称!");
            return;
        }
        if (TextUtils.isEmpty(trainPerson)) {
            ToastUtils.getInstance().showShortToastBottom("请选择培人!");
            return;
        }
        if (TextUtils.isEmpty(participant)) {
            ToastUtils.getInstance().showShortToastBottom("请选择参与人!");
            return;
        }

        AddTrainRecordInput commonInput = new AddTrainRecordInput();
        if (!TextUtils.isEmpty(id)) {
            commonInput.setId(id);
        }
        commonInput.setCbsCourseId(trainCourseId);
        commonInput.setTrainer(trainPersonId);
        commonInput.setTrainingDate(date);
        String[] split = participantId.split(",");
        List<AddTrainRecordInput.CbSTrainRecordUserBean> list = new ArrayList<>();
        for (String s : split) {
            AddTrainRecordInput.CbSTrainRecordUserBean cbSTrainRecordUserBean = new AddTrainRecordInput.CbSTrainRecordUserBean();
            cbSTrainRecordUserBean.setUserId(s);
            list.add(cbSTrainRecordUserBean);
        }
        commonInput.setCbS_TrainRecordUser(list);
        commonInput.setRemarks(remark);
        commonInput.setAnnex(sbPicId.toString());

        Call<String> call = HttpManager.getInstance().requestService().ADD_CONTRACTOR_TRAIN_RECORD(HttpManager.getInstance().requestBody(commonInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                CommonOutput commonOutput = new Gson().fromJson(result, CommonOutput.class);
                if (commonOutput.getResult().equals("Success")) {
                    ToastUtils.getInstance().showShortToastBottom("提交成功!");
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt("SUCCESS", 1);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finishActivity(AddTrainRecordActivity.this);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(commonOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                Bundle bundle = data.getExtras();
                if (bundle == null)
                    return;
                if (resultCode == RESULT_OK) {
                    switch (requestCode) {
                        case 1:
                            participantName = bundle.getString("NAME");
                            participantId = bundle.getString("ID");
                            mTv_train_participant.setText(participantName.substring(0, participantName.length() - 1));
                            break;
                        case Constants.REQUEST_CODE:
                            ArrayList<String> images = data.getStringArrayListExtra(
                                    ImageSelectorUtils.SELECT_RESULT);
                            mPicList.addAll(images);
                            if (mPicList.isEmpty()) {
                                mRv_pic.setVisibility(View.GONE);
                            } else {
                                mRv_pic.setVisibility(View.VISIBLE);
                                mCommonAdapter.notifyDataSetChanged();
                                uploadImages();
                            }
                            break;
                    }
        }
    }

    /**
     * 上传照片
     */
    private void uploadImages() {
        if (mPicList.isEmpty())
            return;
        for (String path : mPicList) {
            File file = new File(path);
            if (!file.exists())
                break;
            final RequestBody requestFile =
                    RequestBody.create(MediaType.parse("application/otcet-stream"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("files", file.getName(), requestFile);

            Call<String> call = HttpManager.getInstance().requestService().UPLOAD_FILE(body);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    UploadFileOutput uploadFileOutput = new Gson().fromJson(response.body(),UploadFileOutput.class);
                    if (uploadFileOutput.getResult().equals("Success")) {
                        String id = uploadFileOutput.getData().get(0).getId();
                        mPicIdList.add(id);
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    // Log.i("Simon", "uploadImages onFailure = " + t.getMessage());
                }
            });
        }
    }

}
